<template>
  <div class="dashboard">
    <div class="header">
      <div class="title">功能中心</div>
      <el-button type="primary" plain size="small" @click="goChat">
        返回对话
      </el-button>
    </div>

    <el-card class="main-card">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="知识库" name="knowledge">
          <div class="section-header">
            <div class="section-title">知识库管理</div>
            <div class="actions">
              <el-select v-model="selectedKB" placeholder="选择知识库" size="small" style="width: 180px"
                @change="loadKnowledgeDocs">
                <el-option v-for="item in knowledgeBases" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
              <el-button type="primary" size="small" @click="kbDialogVisible = true">新建知识库</el-button>
              <el-upload :http-request="onUploadKnowledge" :show-file-list="false" accept=".pdf,.doc,.docx,.txt,.md,.csv">
                <el-button size="small">上传文档</el-button>
              </el-upload>
            </div>
          </div>
          <el-empty v-if="!knowledgeBases.length" description="暂无知识库，先新建一个吧" />
          <div class="kb-list" v-else>
            <el-card v-for="kb in knowledgeBases" :key="kb.id" class="kb-card" :class="{ active: kb.id === selectedKB }"
              @click="selectKB(kb.id)">
              <div class="kb-name">{{ kb.name }}</div>
              <div class="kb-desc">{{ kb.description || '暂无描述' }}</div>
            </el-card>
          </div>
          <div class="section-subtitle" v-if="knowledgeDocs.length">文档列表</div>
          <el-table v-if="knowledgeDocs.length" :data="knowledgeDocs" size="small" stripe>
            <el-table-column prop="title" label="标题" />
            <el-table-column prop="file_name" label="文件名" />
            <el-table-column prop="created_at" label="上传时间" />
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="课表" name="schedule">
          <div class="section-header">
            <div class="section-title">课程安排</div>
            <div class="actions">
              <el-button size="small" @click="loadCourses">刷新</el-button>
              <el-button size="small" type="danger" plain @click="handleClearCourses">清空课程</el-button>
            </div>
          </div>
          <el-form :model="courseForm" label-width="90px" class="mini-form">
            <el-form-item label="课程名">
              <el-input v-model="courseForm.name" placeholder="高等数学" />
            </el-form-item>
            <el-form-item label="星期">
              <el-select v-model="courseForm.weekday" placeholder="选择">
                <el-option v-for="w in weekdays" :key="w.value" :label="w.label" :value="w.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="起止周">
              <div class="inline-input">
                <el-input-number v-model="courseForm.start_week" :min="1" :max="20" />
                <span class="sep">-</span>
                <el-input-number v-model="courseForm.end_week" :min="courseForm.start_week || 1" :max="20" />
              </div>
            </el-form-item>
            <el-form-item label="地点">
              <el-input v-model="courseForm.location" placeholder="教室101" />
            </el-form-item>
            <el-form-item label="教师">
              <el-input v-model="courseForm.teacher" placeholder="张老师" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleCreateCourse">添加课程</el-button>
            </el-form-item>
          </el-form>

          <div class="section-subtitle" v-if="courses.length">全部课程</div>
          <el-table v-if="courses.length" :data="courses" size="small" stripe>
            <el-table-column prop="name" label="课程名" width="140" />
            <el-table-column prop="weekday" label="星期" width="80">
              <template #default="{ row }">
                {{ weekdayLabel(row.weekday) }}
              </template>
            </el-table-column>
            <el-table-column prop="location" label="地点" />
            <el-table-column prop="teacher" label="教师" width="100" />
            <el-table-column label="周次" width="120">
              <template #default="{ row }">
                第 {{ row.start_week }} - {{ row.end_week }} 周
              </template>
            </el-table-column>
          </el-table>

          <div class="section-subtitle" v-if="todayCourses.length">今日课程</div>
          <el-timeline v-if="todayCourses.length" class="today-line">
            <el-timeline-item v-for="item in todayCourses" :key="item.id" color="#409EFF">
              <div class="line-title">{{ item.name }}</div>
              <div class="line-desc">{{ item.location }} · {{ item.teacher }}</div>
            </el-timeline-item>
          </el-timeline>
          <el-empty v-if="!courses.length && !todayCourses.length" description="暂无课程" />
        </el-tab-pane>

        <el-tab-pane label="学习路径" name="learning">
          <div class="section-header">
            <div class="section-title">学习路径</div>
            <div class="actions">
              <el-button size="small" @click="loadLearning">刷新</el-button>
            </div>
          </div>
          <el-empty v-if="!paths.length" description="暂无学习路径" />
          <div class="path-grid">
            <el-card v-for="item in paths" :key="item.id" class="path-card" @click="loadPathDetail(item.id)">
              <div class="path-name">{{ item.name }}</div>
              <div class="path-desc">{{ item.description || '暂无描述' }}</div>
              <div class="path-meta">
                <span>节点: {{ item.node_count || '--' }}</span>
                <span>进度: {{ item.progress || 0 }}%</span>
              </div>
            </el-card>
          </div>
          <el-card v-if="activePath" class="detail-card">
            <div class="detail-title">{{ activePath.name }}</div>
            <div class="detail-desc">{{ activePath.description || '暂无描述' }}</div>
            <div class="detail-meta">状态：{{ activePath.status || '未开始' }}</div>
          </el-card>

          <div class="section-subtitle" v-if="reviews.length">今日复习任务</div>
          <el-timeline v-if="reviews.length" class="today-line">
            <el-timeline-item v-for="task in reviews" :key="task.id" color="#67C23A">
              <div class="line-title">{{ task.title || task.name }}</div>
              <div class="line-desc">{{ task.description || '请按时复习' }}</div>
            </el-timeline-item>
          </el-timeline>
        </el-tab-pane>

        <el-tab-pane label="教务抓取" name="course">
          <div class="section-header">
            <div class="section-title">绑定学号</div>
            <div class="actions">
              <el-button size="small" @click="loadStudentInfo">查询绑定</el-button>
              <el-button size="small" @click="loadDailyText(1)">今日课表文本</el-button>
            </div>
          </div>
          <el-form :model="studentForm" label-width="100px" class="mini-form">
            <el-form-item label="学号">
              <el-input v-model="studentForm.student_id" placeholder="20230001" />
            </el-form-item>
            <el-form-item label="密码">
              <el-input v-model="studentForm.student_password" type="password" show-password />
            </el-form-item>
            <el-form-item label="QQ">
              <el-input v-model="studentForm.qq" />
            </el-form-item>
            <el-form-item label="微信">
              <el-input v-model="studentForm.vx" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleBindStudent">绑定并抓取</el-button>
            </el-form-item>
          </el-form>
          <el-card v-if="studentInfo" class="detail-card">
            <div class="detail-title">绑定信息</div>
            <div class="detail-desc">学号：{{ studentInfo.student_id }}</div>
            <div class="detail-desc">更新于：{{ studentInfo.updated_at || studentInfo.created_at || '--' }}</div>
          </el-card>
          <el-card v-if="dailyText" class="detail-card">
            <div class="detail-title">课表文本</div>
            <div class="detail-desc pre">{{ dailyText }}</div>
          </el-card>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <el-dialog v-model="kbDialogVisible" title="新建知识库" width="400px">
      <el-form :model="kbForm" label-width="80px">
        <el-form-item label="名称">
          <el-input v-model="kbForm.name" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="kbForm.description" type="textarea" rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="kbDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreateKB">创建</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { getToken } from "@/utils/setToken";
import {
  fetchKnowledgeBases,
  fetchKnowledgeDocuments,
  createKnowledgeBase,
  uploadKnowledgeDocument
} from "@/api/api/knowledge";
import {
  fetchCourses,
  createCourse,
  fetchTodayCourses,
  clearCourses
} from "@/api/api/schedule";
import {
  fetchLearningPaths,
  fetchLearningPathDetail,
  fetchTodayReviews
} from "@/api/api/learning";
import {
  bindStudentInfo,
  fetchStudentInfo,
  fetchFlagDayCourse
} from "@/api/api/course";

const router = useRouter();
const activeTab = ref("knowledge");

// 知识库
const knowledgeBases = reactive([]);
const knowledgeDocs = reactive([]);
const selectedKB = ref(null);
const kbDialogVisible = ref(false);
const kbForm = reactive({ name: "", description: "" });

const loadKnowledgeBases = async () => {
  if (!getToken()) return;
  const res = await fetchKnowledgeBases().catch(() => []);
  knowledgeBases.splice(0, knowledgeBases.length, ...(Array.isArray(res?.results) ? res.results : res));
  if (!selectedKB.value && knowledgeBases.length) {
    selectedKB.value = knowledgeBases[0].id;
  }
  if (selectedKB.value) {
    await loadKnowledgeDocs();
  }
};

const selectKB = (id) => {
  selectedKB.value = id;
  loadKnowledgeDocs();
};

const loadKnowledgeDocs = async () => {
  if (!selectedKB.value) {
    knowledgeDocs.splice(0, knowledgeDocs.length);
    return;
  }
  const res = await fetchKnowledgeDocuments({ knowledge_base_id: selectedKB.value }).catch(() => []);
  const data = Array.isArray(res?.results) ? res.results : res;
  knowledgeDocs.splice(0, knowledgeDocs.length, ...data);
};

const handleCreateKB = async () => {
  if (!kbForm.name.trim()) {
    ElMessage.error("请输入名称");
    return;
  }
  await createKnowledgeBase(kbForm).catch((e) => {
    throw e;
  });
  ElMessage.success("创建成功");
  kbDialogVisible.value = false;
  kbForm.name = "";
  kbForm.description = "";
  loadKnowledgeBases();
};

const onUploadKnowledge = async (options) => {
  const { file, onError, onSuccess } = options;
  if (!selectedKB.value) {
    ElMessage.error("请先选择知识库");
    onError && onError();
    return;
  }
  const form = new FormData();
  form.append("file", file);
  form.append("knowledge_base_id", selectedKB.value);
  form.append("title", file.name);
  try {
    const res = await uploadKnowledgeDocument(form);
    await loadKnowledgeDocs();
    ElMessage.success("上传成功");
    onSuccess && onSuccess(res);
  } catch (error) {
    ElMessage.error(error?.message || "上传失败");
    onError && onError(error);
  }
};

// 课表
const weekdays = [
  { label: "周一", value: 1 },
  { label: "周二", value: 2 },
  { label: "周三", value: 3 },
  { label: "周四", value: 4 },
  { label: "周五", value: 5 },
  { label: "周六", value: 6 },
  { label: "周日", value: 7 },
];
const courseForm = reactive({
  name: "",
  weekday: null,
  start_week: 1,
  end_week: 16,
  location: "",
  teacher: "",
});
const courses = reactive([]);
const todayCourses = reactive([]);

const loadCourses = async () => {
  const res = await fetchCourses().catch(() => []);
  const data = Array.isArray(res?.results) ? res.results : res;
  courses.splice(0, courses.length, ...data);
  const todayRes = await fetchTodayCourses().catch(() => []);
  todayCourses.splice(0, todayCourses.length, ...(Array.isArray(todayRes?.results) ? todayRes.results : todayRes));
};

const handleCreateCourse = async () => {
  if (!courseForm.name || !courseForm.weekday) {
    ElMessage.error("请填写课程名和星期");
    return;
  }
  await createCourse(courseForm).catch((e) => {
    throw e;
  });
  ElMessage.success("添加成功");
  Object.assign(courseForm, {
    name: "",
    weekday: null,
    start_week: 1,
    end_week: 16,
    location: "",
    teacher: "",
  });
  loadCourses();
};

const handleClearCourses = async () => {
  await clearCourses().catch(() => {
    ElMessage.error("清空失败");
  });
  ElMessage.success("已清空课程");
  courses.splice(0, courses.length);
  todayCourses.splice(0, todayCourses.length);
};

const weekdayLabel = (v) => {
  const item = weekdays.find((i) => i.value === v);
  return item ? item.label : v;
};

// 学习路径
const paths = reactive([]);
const activePath = ref(null);
const reviews = reactive([]);

const loadLearning = async () => {
  const res = await fetchLearningPaths().catch(() => []);
  paths.splice(0, paths.length, ...(Array.isArray(res?.results) ? res.results : res));
  if (paths.length) {
    await loadPathDetail(paths[0].id);
  }
  const reviewRes = await fetchTodayReviews().catch(() => []);
  reviews.splice(0, reviews.length, ...(Array.isArray(reviewRes?.results) ? reviewRes.results : reviewRes));
};

const loadPathDetail = async (id) => {
  const res = await fetchLearningPathDetail(id).catch(() => null);
  activePath.value = res;
};

// 教务抓取
const studentForm = reactive({
  student_id: "",
  student_password: "",
  qq: "",
  vx: "",
});
const studentInfo = ref(null);
const dailyText = ref("");

const handleBindStudent = async () => {
  if (!studentForm.student_id || !studentForm.student_password) {
    ElMessage.error("请填写学号和密码");
    return;
  }
  await bindStudentInfo(studentForm).catch((e) => {
    throw e;
  });
  ElMessage.success("绑定成功");
  loadStudentInfo();
};

const loadStudentInfo = async () => {
  if (!studentForm.student_id) {
    ElMessage.error("请输入学号后查询");
    return;
  }
  const res = await fetchStudentInfo({ student_id: studentForm.student_id }).catch(() => null);
  if (res) {
    studentInfo.value = res?.results ? res.results[0] : res;
  }
};

const loadDailyText = async (flag = 1) => {
  if (!studentForm.student_id) {
    ElMessage.error("请输入学号");
    return;
  }
  const res = await fetchFlagDayCourse({ flag, student_id: studentForm.student_id }).catch(() => null);
  dailyText.value = res?.text || JSON.stringify(res || {});
};

const goChat = () => {
  router.push({ path: "/index" });
};

onMounted(() => {
  if (!getToken()) {
    ElMessage.warning("请先登录以使用全部功能");
    router.push({ path: "/login" });
    return;
  }
  loadKnowledgeBases();
  loadCourses();
  loadLearning();
});
</script>

<style scoped lang="scss">
.dashboard {
  min-height: 100vh;
  background: #f5f8fa;
  padding: 20px 30px;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 14px;

  .title {
    font-size: 22px;
    font-weight: 600;
    color: #0f3758;
  }
}

.main-card {
  border-radius: 12px;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.06);
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
}

.section-subtitle {
  margin: 18px 0 10px;
  font-weight: 600;
  color: #0f3758;
}

.actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.kb-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 12px;
  margin-bottom: 12px;
}

.kb-card {
  border: 1px solid #e6f0f3;
  cursor: pointer;

  &.active {
    border-color: #0f3758;
  }

  .kb-name {
    font-weight: 600;
    color: #0f3758;
  }

  .kb-desc {
    margin-top: 8px;
    color: #666;
    font-size: 13px;
  }
}

.mini-form {
  background: #f9fbfd;
  padding: 12px;
  border-radius: 8px;
  margin-bottom: 16px;
}

.inline-input {
  display: flex;
  align-items: center;
  gap: 6px;

  .sep {
    color: #99a;
  }
}

.today-line {
  margin-top: 8px;
}

.line-title {
  font-weight: 600;
  color: #0f3758;
}

.line-desc {
  color: #666;
}

.path-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 12px;
}

.path-card {
  cursor: pointer;
  border: 1px solid #e6f0f3;

  .path-name {
    font-weight: 600;
    color: #0f3758;
  }

  .path-desc {
    margin: 6px 0;
    color: #666;
  }

  .path-meta {
    display: flex;
    justify-content: space-between;
    color: #888;
    font-size: 12px;
  }
}

.detail-card {
  margin-top: 14px;
  background: #f9fbfd;

  .detail-title {
    font-weight: 700;
    color: #0f3758;
    margin-bottom: 6px;
  }

  .detail-desc {
    color: #555;
    line-height: 1.5;

    &.pre {
      white-space: pre-wrap;
      font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;
    }
  }

  .detail-meta {
    margin-top: 6px;
    color: #777;
  }
}
</style>
